package eproject.mm.com.projectsupervision.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;

import eproject.mm.com.projectsupervision.MainActivity;
import eproject.mm.com.projectsupervision.PrjApplication;
import eproject.mm.com.projectsupervision.R;
import eproject.mm.com.projectsupervision.constant.Constant;
import eproject.mm.com.projectsupervision.fragment.ProfileFragment;
import eproject.mm.com.projectsupervision.util.HttpUtil;
import eproject.mm.com.projectsupervision.util.ServiceUtil;
import eproject.mm.com.projectsupervision.util.TimeUtil;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

import static eproject.mm.com.projectsupervision.util.HttpUtil.okHttpClient;

public class DemoService extends Service implements SensorEventListener {
    private NotificationManager notificationManager;
    private Notification.Builder builder;
    private Intent nfIntent;

    public LocationService locationService;
    private SensorManager sensorManager;
    SharedPreferences userSettings;
    SharedPreferences.Editor editor;
    MyStepRestReceiver receiver;
    //private Messenger messenger = new Messenger(new MessengerHandler());

    private String Process_Name = "eproject.mm.com.projectsupervision:KeepService";

    public DemoService() {
    }

    private StrongService startS2 = new StrongService.Stub() {
        @Override
        public void stopService() throws RemoteException {
            Intent i = new Intent(getBaseContext(), KeepService.class);
            getBaseContext().stopService(i);
        }

        @Override
        public void startService() throws RemoteException {
            Intent i = new Intent(getBaseContext(), KeepService.class);
            getBaseContext().startService(i);
        }
    };

    @Override
    public void onCreate() {
        //android.os.Debug.waitForDebugger();
        super.onCreate();
        //init();

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

        //keepService();
    }

    @Override
    public void onTrimMemory(int level){
        super.onTrimMemory(level);
    }

    private  void keepService(){
        boolean isRun = ServiceUtil.isProessRunning(DemoService.this, Process_Name);
        if (isRun == false) {
            try {
                startS2.startService();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

//    private LocationBinder locationBinder = new LocationBinder();
//    @Override
//    public IBinder onBind(Intent intent) {
//        // TODO: Return the communication channel to the service.
//        return locationBinder;
//    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        builder = new Notification.Builder(this.getApplicationContext());
        nfIntent = new Intent(this, MainActivity.class);

        locationService = new LocationService(getApplicationContext());
        locationService.registerListener(mListener);
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();

        builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0))
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher))
                .setContentTitle("项目管理") // 设置下拉列表里的标题
                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                .setContentText("系统正在记录您的工作轨迹、行动步数"); // 设置上下文内容

        Notification demoNotification = builder.build();
        startForeground(110, demoNotification);// 开始前台服务

        Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        if (countSensor != null) {
            sensorManager.registerListener(DemoService.this, countSensor, SensorManager.SENSOR_DELAY_NORMAL);
        }

        userSettings = getApplicationContext().getSharedPreferences("setting", Context.MODE_MULTI_PROCESS);
        editor = userSettings.edit();

        hasRecord = false;

        Bundle bundle = intent.getExtras();
        if(bundle.containsKey("flag")) {
            int _flag = bundle.getInt("flag");
            if (_flag == 1) {
                resetCount = true;
            } else {
                resetCount = false;
            }
        }
        receiver = new MyStepRestReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(PrjApplication.getInstance().RestStepCountAction);
        registerReceiver(receiver, filter);

//        Intent intents = new Intent();
//        intents.setClass(this, KeepService.class);
//        bindService(intents, conn, Context.BIND_IMPORTANT);

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        hasRecord = false;
        locationService.stop();
        unregisterReceiver(receiver);
        sensorManager.unregisterListener(DemoService.this);
        super.onDestroy();
        //主界面中需要手动调用stop方法service才会结束
        stopForeground(true);
    }

//    @Override
//    public boolean onUnbind(Intent intent) {
//        return super.onUnbind(intent);
//    }


//    private class MessengerHandler extends Handler {
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case Constant.MSG_FROM_CLIENT:
//                    break;
//                default:
//                    super.handleMessage(msg);
//            }
//        }
//    }

//    class LocationBinder extends Binder{
//
//    }

    String localString = "";
    int localType;
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {

                String _str = location.getLongitude()+","+location.getLatitude();
                //if(!localString.equals(_str)){
                    localString = _str;
                    localType = location.getLocType();
                    //上传
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Request.Builder builder=new Request.Builder();
                                String token = userSettings.getString("authenticationtoken","");
                                builder.addHeader("authenticationToken",token);
                                Request request=builder.get().url("http://"+ PrjApplication.getInstance().getServerIp() +":"+PrjApplication.getInstance().getServerPort()+"/"+PrjApplication.getInstance().getPreFixPath()+"/insertPos?pos="+localString+"&loctype="+localType).build();

                                Call call = HttpUtil.okHttpClient.newCall(request);
                                //同步GET请求
                                try {
                                    Response response=call.execute();

                                }catch (Exception e){
                                    e.printStackTrace();
                                }

                                Intent intent = new Intent(PrjApplication.getInstance().LocalAction);
                                sendBroadcast(intent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                //}

            }
        }
    };

    boolean hasRecord = false;
    int currDayCount = 0;
    private int previousStepCount;
    boolean resetCount = false;
    @Override
    public void onSensorChanged(SensorEvent event) {
        int tempStep = (int) event.values[0];
        if(!hasRecord){
            if(resetCount){
                currDayCount = 0;
            }else {
                userSettings = getApplicationContext().getSharedPreferences("setting", 0);
                currDayCount = userSettings.getInt("stepCount", 0);
            }
            previousStepCount = tempStep;
            hasRecord = true;
        }else {
            int tempCount = tempStep - previousStepCount;
            previousStepCount = tempStep;
            currDayCount += tempCount;

            editor.putInt("stepCount",currDayCount).commit();

            Intent intent = new Intent(PrjApplication.getInstance().StepAction);
            intent.putExtra("step",currDayCount);
            sendBroadcast(intent);
        }
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public class MyStepRestReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            if(action.equals(PrjApplication.getInstance().RestStepCountAction)){
                resetCount = true;
            }
        }
    }

    private ServiceConnection conn;
    private MyService myService;

    @Override
    public IBinder onBind(Intent intent) {
        return myService;
    }
    private void init() {
        if (conn == null) {
            conn = new MyServiceConnection();
        }
        myService = new MyService();
    }
    class MyService extends StrongService.Stub {
        @Override
        public void startService() throws RemoteException {
        }
        @Override
        public void stopService() throws RemoteException {
        }
    }
    class MyServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(this.getClass().getName(),"******************----Local Connect----******************");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            DemoService.this.startService(new Intent(DemoService.this,
                    KeepService.class));
            DemoService.this.bindService(new Intent(DemoService.this,
                    KeepService.class), conn, Context.BIND_IMPORTANT);

        }

    }
}
